import React, { useState, useCallback, useEffect, useContext } from 'react'
import { useHistory } from 'react-router-dom'
import { postSofContractFindContract, getSofContractExecuteContract } from '../Api'
import { myContext } from '../../../reducer'
import { ContractType } from '../../../assets/enum'
import SelectModule from './Components/SelectModule'
import { SignContractAll } from './style'
import { PageHeader, Button, Table, Space, message, Modal } from 'antd'
import moment from 'moment'
import { ExclamationCircleOutlined } from '@ant-design/icons';
const { confirm } = Modal;

/**
 * @description: 合同列表
 * @author: xiaoxujs
 * @updata: xiaoxujs（2021-08-01） 编辑合同
 */

const ContractList = () => {
    const history = useHistory()
    const { state } = useContext(myContext)
    const [listData, setListData] = useState([]) //list
    const [total, setTotal] = useState(0) // total
    const [currentPage, setCurrentPage] = useState(1) //当前页
    const [size, setSize] = useState(10) //当页条数
    const [selectData, setSelectData] = useState({}) // 搜索数据
    const listFun = useCallback(
        (parames = {
            currentPage: 1,
            size: 10
        }) => {
            parames.state = state.contractType
                ; (async () => {
                    const { code, msg, data } = await postSofContractFindContract(parames)
                    if (code === '20000') {
                        setListData(data.records)
                        setTotal(data.total)
                        setCurrentPage(parames.currentPage)
                        setSize(parames.size)
                    } else {
                        message.error(msg)
                    }
                })()
        },
        [state.contractType],
    )
    useEffect(() => {
        listFun()
    }, [listFun])
    //进入添加合同页面
    const handleAddSignContract = () => {
        history.push('/addContract')
    }
    const handleSelectDataFun = values => {
        if(values.time) {
            values.startTime = moment(values.time[0]).format('YYYY-MM-DD')
            values.endTime = moment(values.time[1]).format('YYYY-MM-DD')
            delete values.time
        }

        setSelectData(values)
        const parames = {
            ...values,
            currentPage: 1,
            size: 10
        }
        listFun(parames);
    }
    //分页
    const pagination = {
        //是否可以改变pagesize//
        showSizeChanger: true,
        //是否可以快速跳转到某页
        showQuickJumper: true,
        //展示一共有多少条数据//
        showTotal: () => `共${total}条`,
        //每页条数
        pageSize: size,
        //当前页数
        current: currentPage,
        //数据总数
        total: total,
        //pageSize 变化的回调
        onShowSizeChange: (current, pageSize) => changePageSize(pageSize, current),
        //页码改变的回调，参数是改变后的页码及每页条数
        onChange: (current) => changePage(current),
    }
    //改变每页条数
    const changePageSize = (pageSizeFun, current) => {
        const parames = {
            ...selectData,
            currentPage: current,
            size: pageSizeFun
        }
        listFun(parames);
    }
    //改变页数
    const changePage = (current) => {
        const parames = {
            ...selectData,
            currentPage: current,
            size
        }
        listFun(parames);
    }
    //编辑合同
    const handleChangeContract = (id) => {
        history.push({pathname : '/addContract', state: {
            contractId: id
        }}  )
    }
    //执行合同
    const handleNeExecuteContract = contractId => {
        confirm({
            title: '确定要执行当前合同吗?',
            icon: <ExclamationCircleOutlined />,
            onOk() {
                ; (async () => {
                    const { code, msg } = await getSofContractExecuteContract({ contractId })
                    if (code === '20000') {
                        message.success('执行成功！')
                        const parames = {
                            ...selectData,
                            currentPage,
                            size
                        }
                        listFun(parames);
                    } else {
                        message.error(msg)
                    }
                })()
            }
        });
    }
    //进入收款计划页面
    const handleMoneyPlan = (conNo) => {
        history.push({
            pathname: '/contractMoneyPlan', state: {
                conNo
            }
        })
    }
    //进入合同编号
    const handleEnterDetails = (conNo, id) => {
        history.push({pathname: '/contractListDetails', state: {
            conNo,
            id
        }})
    }
    const columns = [
        {
            title: '#',
            render: (text, recode, index) => <span>{index + 1}</span>
        },
        {
            title: '客户名称',
            dataIndex: 'clientName',
            render: (text, recode) => <Button type = 'link' onClick = {() => handleEnterDetails(recode.conNo, recode.id)} >{text}</Button>
        },
        {
            title: '合同编号',
            dataIndex: 'conNo'
        },
        {
            title: '签约时间',
            dataIndex: 'concludeDate'
        },
        {
            title: '合同状态',
            dataIndex: 'state'
        },
        {
            title: '销售人员',
            dataIndex: 'sellName'
        },
        {
            title: '副负责人',
            dataIndex: 'asMainName'
        },
        {
            title: '经办人',
            dataIndex: 'inputName'
        },
        {
            title: '操作',
            render: (text, recode) => <Space>
                {
                    state.contractType === 0
                        ?
                        <>
                            <Button type='primary' onClick={() => handleChangeContract(recode.id)}>编辑</Button>
                            <Button type='primary' onClick={() => handleNeExecuteContract(recode.id)}>执行</Button>
                        </>
                        :
                        null
                }
                {
                    state.contractType === 1
                        ?
                        <>
                            <Button type='primary' onClick={() => handleMoneyPlan(recode.conNo)}>收款计划</Button>
                        </>
                        :
                        null
                }

            </Space>
        }
    ];
    return <SignContractAll>
        <PageHeader
            className="site-page-header"
            title={ContractType[state.contractType]}
            extra={[
                <Button key="1" type="primary" onClick={() => handleAddSignContract()}>
                    新增签约合同
                </Button>
            ]}
        ></PageHeader>
        <SelectModule handleSelectDataFun={handleSelectDataFun} setSelectData={setSelectData} listFun={listFun} />
        <Table dataSource={listData} columns={columns} pagination={pagination} rowKey='id' />
    </SignContractAll>
}

export default ContractList